#-*-coding:utf-8-*-
# Create your views here.
import time,datetime

from django.core.paginator import Paginator, InvalidPage
from django.shortcuts import get_object_or_404,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.template import loader, RequestContext
import os,sys
import md5,random
import Image
from crm.models import Members
from crm.models import Salesperson
from crm.models import Agent
from crm.models import Projects,Project_course_info
from crm.models import Sales_record
from crm.models import Follow_up
from crm.common import login_required
from pagination import PaginationWrap

from crmv2.models import Student,Program_student_course,Student_Payment_Record

from crm import logClass as log

log = log.Log()
"""学生查找"""
@login_required
def search (request):

    agent_list = Agent.objects.order_by('id')
    project_list = Projects.objects.order_by('id')
    if request.method == 'GET':
        page=int(request.GET.get('page','1'))

        """
        try:
            p_id=request.session['program']
            is_p='y'
        except:
            p_id=request.GET.get('p_id','0')
            is_p=''
        """
        p_id=request.GET.get('p_id','')

        if p_id=='':
            p_id=request.session['program']

        a_id=request.GET.get('a_id','0')
        sales=request.GET.get('sales','')
        name=request.GET.get('name','')
        tel=request.GET.get('tel','')
        email=request.GET.get('email','')
        start_date=request.GET.get('start_date')
        end_date=request.GET.get('end_date')
        last_contact = request.GET.get('last_contact','none')
        
        try:
            p_obj=Projects.objects.get(pk=int(p_id))
        except:
            p_obj=''

        students=Student.objects.filter()
        if start_date and end_date!='begin':
            students=students.filter(applytime__gte=start_date)

        if end_date and end_date!='now':
            students=students.filter(applytime__lte=end_date)


        if p_id !='0':
            students=students.filter(program__pk=int(p_id))
        if a_id !='0':
            students=students.filter(agent__pk=int(a_id))
        from django.db.models import Q
        if name:
            nameup=name.capitalize()
            students=students.filter(Q(name_en__icontains=name)|Q(name_en__icontains=nameup))
        if tel:
            students=students.filter(Q(tel_h__contains=tel)|Q(tel_o__contains=tel)|Q(tel_m__contains=tel))
        if email:
            students=students.filter(email__icontains=email)
      
#        if request.session['level']=='sales':
#            members=members.filter(salesperson__id=request.session['id'])
#        else:
        if sales:
            students=students.filter(salesperson__name=sales)
        import datetime
        if last_contact != 'none':
            nowtime = datetime.datetime.now()
            students=students.filter(last_contact__lte=last_contact)
        
        students=students.order_by('-student_id')

        members_list=apage_list=temp_list=[]
        today=datetime.date.today()
        #startid=30*(int(page)-1)
        #endid=30*int(page)
        #temp_list=members[startid:endid]
        
        paginator=Paginator(students,30)
        page=int(page)
        curPage = paginator.page(page)
        pw = PaginationWrap(paginator,page,request)
        #members_list=members
        for m in curPage.object_list:
            m_dict={}
            m_dict['id']=m.id
            try:
                m_dict['salesperson']=m.salesperson
            except:
                m_dict['salesperson']=''
            m_dict['student_id']=m.student_id
            if m.fullname:
                m_dict['name']=m.fullname
            else:
                m_dict['name']=m.name_en
            m_dict['last_name']=m.last_name
            m_dict['first_name']=m.first_name
            m_dict['tel_h']=m.tel_h
            m_dict['tel_o']=m.tel_o
            m_dict['tel_m']=m.tel_m
            m_dict['email']=m.email
            sdate=m.start_date
            try:
                sdate=sdate.date(*[int(i) for i in formday.split('-')])
            except:
                pass
            m_dict['start_date']=sdate
            
            m_dict['address']=m.address
            try:
                m_dict['agent']=m.agent
            except:
                m_dict['agent']=''
            
            try:
                m_dict['program']=m.program
            except:
                m_dict['program']=''
            
            m_dict['applytime']=m.applytime
            try:
                if m.referee is None:
                    m_dict['referee']=None
                else:
                    m_dict['referee']=m.referee
            except Exception,e:
                log.info(e)
            today=str(today)
            toy=today[:4]
            tom=today[5:7]
            tod=today[8:10]
            m_dict['isgray']=m_dict['isblack']=m_dict['othercolor']=''
            
            
            if m_dict['isgray'] or m_dict['isblack']:
                m_dict['othercolor']=1

            #module complated num
            module_completed_num=Program_student_course.objects.filter(student=m,is_removed=0,status='Completed').count()
            m_dict['module_completed_num']=module_completed_num
            #Next payment date
            nextpayment=''
            m_dict['fullpay']=0
            try:
                sp_obj=Student_Payment_Record.objects.get(student=m)
                m_dict['fullpay']=sp_obj.fullpay
                if sp_obj.date1_invoice=='' or sp_obj.date1_paid=='' or sp_obj.date1_paiy_by=='' or sp_obj.date1_handed_by=='':
                    nextpayment=datetime.datetime.strftime(sp_obj.date1,'%d/%m/%Y')
                else:
                    if sp_obj.date2_invoice=='' or sp_obj.date2_paid=='' or sp_obj.date2_paiy_by=='' or sp_obj.date2_handed_by=='':
                        nextpayment=sp_obj.date2
                    else:
                        if sp_obj.date3_invoice=='' or sp_obj.date3_paid=='' or sp_obj.date3_paiy_by=='' or sp_obj.date3_handed_by=='':
                            nextpayment=sp_obj.date3
                        else:
                            if sp_obj.date4_invoice=='' or sp_obj.date4_paid=='' or sp_obj.date4_paiy_by=='' or sp_obj.date4_handed_by=='':
                                nextpayment=sp_obj.date4
                
            except:
                pass
            '''
            npdate=''
            if nextpayment:
                npdate=nextpayment[6:10]+'-'+nextpayment[3:5]+'-'+nextpayment[:2]
                npdate=time.strptime(npdate,'%Y-%m-%d')
                yy, mm, dd =npdate[0:3]
                npdate =datetime.datetime(yy, mm, dd)
            '''
            m_dict['nextpayment']=nextpayment
                
            apage_list.append(m_dict)


        #try:
            #page=int(page)
            #if page > paginator.pages:
            #    page=paginator.pages
            #if page < 1:
            #    page=1
        #except:
            #return HttpResponseRedirect('/ulist')
        querystr="page=1";
        for k,v in request.GET.items():
            querystr = querystr + "&" + k + "=" + v;
            
        return render_to_response('stulist.html',{
        'pw':pw,
        'pageurl':'/v2/stusearch/',           
        'students_list':apage_list,
        'level':request.session['level'],
        'issearch':"y",
        'p_id':int(p_id),
        'a_id':int(a_id),
        'sales':sales,
        'name':name,
        'email':email,
        'tel':tel,
        'project_list':project_list,
        'agent_list':agent_list,
        'start_date':start_date,
        'end_date':end_date,
        'p_obj':p_obj,
        })


def alunmi(request):
    agent_list = Agent.objects.order_by('id')
    project_list = Projects.objects.order_by('id')
    if request.method == 'GET':
        page=int(request.GET.get('page','1'))

        """
        try:
            p_id=request.session['program']
            is_p='y'
        except:
            p_id=request.GET.get('p_id','0')
            is_p=''
        """
        p_id=request.GET.get('p_id','0')

        if p_id=='':
            p_id=request.session['program']

        a_id=request.GET.get('a_id','0')
        sales=request.GET.get('sales','')
        name=request.GET.get('name','')
        tel=request.GET.get('tel','')
        email=request.GET.get('email','')
        start_date=request.GET.get('start_date')
        end_date=request.GET.get('end_date')
        last_contact = request.GET.get('last_contact','none')
        
        try:
            p_obj=Projects.objects.get(pk=int(p_id))
        except:
            p_obj=''

        students=Student.objects.filter(program__pk__in=[3,4,16,17,21])
        if start_date and end_date!='begin':
            students=students.filter(applytime__gte=start_date)

        if end_date and end_date!='now':
            students=students.filter(applytime__lte=end_date)


        if p_id !='0':
            students=students.filter(program__pk=int(p_id))
        if a_id !='0':
            students=students.filter(agent__pk=int(a_id))
        from django.db.models import Q
        if name:
            nameup=name.capitalize()
            students=students.filter(Q(name_en__icontains=name)|Q(name_en__icontains=nameup))
        if tel:
            students=students.filter(Q(tel_h__contains=tel)|Q(tel_o__contains=tel)|Q(tel_m__contains=tel))
        if email:
            students=students.filter(email__icontains=email)
      
#        if request.session['level']=='sales':
#            members=members.filter(salesperson__id=request.session['id'])
#        else:
        if sales:
            students=students.filter(salesperson__name=sales)
        import datetime
        if last_contact != 'none':
            nowtime = datetime.datetime.now()
            students=students.filter(last_contact__lte=last_contact)
        
        students=students.order_by('-student_id')

        members_list=apage_list=temp_list=[]
        today=datetime.date.today()
        #startid=30*(int(page)-1)
        #endid=30*int(page)
        #temp_list=members[startid:endid]
        
        paginator=Paginator(students,30)
        page=int(page)
        curPage = paginator.page(page)
        pw = PaginationWrap(paginator,page,request)
        #members_list=members
        for m in curPage.object_list:
            #module complated num
            m_dict={}
            module_completed_num=Program_student_course.objects.filter(student=m,is_removed=0,status='Completed').count()
            if (m.program.id==16 and module_completed_num>=15) or (m.program.id==4 and module_completed_num>=11) or (m.program.id==3 and module_completed_num>=5) or (m.program.id==17 and module_completed_num>=5) or (m.program.id==10 and module_completed_num>=2) or (m.program.id==21 and module_completed_num>=1):
                m_dict['module_completed_num']=module_completed_num

                m_dict['id']=m.id
                try:
                    m_dict['salesperson']=m.salesperson
                except:
                    m_dict['salesperson']=''
                m_dict['student_id']=m.student_id
                if m.fullname:
                    m_dict['name']=m.fullname
                else:
                    m_dict['name']=m.name_en
                m_dict['last_name']=m.last_name
                m_dict['first_name']=m.first_name
                m_dict['tel_h']=m.tel_h
                m_dict['tel_o']=m.tel_o
                m_dict['tel_m']=m.tel_m
                m_dict['email']=m.email
                sdate=m.start_date
                try:
                    sdate=sdate.date(*[int(i) for i in formday.split('-')])
                except:
                    pass
                m_dict['start_date']=sdate
                
                m_dict['address']=m.address
                try:
                    m_dict['agent']=m.agent
                except:
                    m_dict['agent']=''
                
                try:
                    m_dict['program']=m.program
                except:
                    m_dict['program']=''
                
                m_dict['applytime']=m.applytime
                try:
                    if m.referee is None:
                        m_dict['referee']=None
                    else:
                        m_dict['referee']=m.referee
                except Exception,e:
                    log.info(e)
                today=str(today)
                toy=today[:4]
                tom=today[5:7]
                tod=today[8:10]
                m_dict['isgray']=m_dict['isblack']=m_dict['othercolor']=''
                
                
                if m_dict['isgray'] or m_dict['isblack']:
                    m_dict['othercolor']=1

                #Next payment date
                nextpayment=''
                m_dict['fullpay']=0
                try:
                    sp_obj=Student_Payment_Record.objects.get(student=m)
                    m_dict['fullpay']=sp_obj.fullpay
                    if sp_obj.date1_invoice=='' or sp_obj.date1_paid=='' or sp_obj.date1_paiy_by=='' or sp_obj.date1_handed_by=='':
                        nextpayment=datetime.datetime.strftime(sp_obj.date1,'%d/%m/%Y')
                    else:
                        if sp_obj.date2_invoice=='' or sp_obj.date2_paid=='' or sp_obj.date2_paiy_by=='' or sp_obj.date2_handed_by=='':
                            nextpayment=sp_obj.date2
                        else:
                            if sp_obj.date3_invoice=='' or sp_obj.date3_paid=='' or sp_obj.date3_paiy_by=='' or sp_obj.date3_handed_by=='':
                                nextpayment=sp_obj.date3
                            else:
                                if sp_obj.date4_invoice=='' or sp_obj.date4_paid=='' or sp_obj.date4_paiy_by=='' or sp_obj.date4_handed_by=='':
                                    nextpayment=sp_obj.date4
                    
                except:
                    pass
                npdate=''
                if nextpayment:
                    npdate=nextpayment[6:10]+'-'+nextpayment[3:5]+'-'+nextpayment[:2]
                    npdate=time.strptime(npdate,'%Y-%m-%d')
                    yy, mm, dd =npdate[0:3]
                    npdate =datetime.datetime(yy, mm, dd)
                m_dict['nextpayment']=npdate
                    
                apage_list.append(m_dict)
            else:
                continue

        #try:
            #page=int(page)
            #if page > paginator.pages:
            #    page=paginator.pages
            #if page < 1:
            #    page=1
        #except:
            #return HttpResponseRedirect('/ulist')
        querystr="page=1";
        for k,v in request.GET.items():
            querystr = querystr + "&" + k + "=" + v;
            
        return render_to_response('alunmi.html',{
        'pw':pw,
        'pageurl':'/v2/stusearch/',           
        'students_list':apage_list,
        'level':request.session['level'],
        'issearch':"y",
        'p_id':int(p_id),
        'a_id':int(a_id),
        'sales':sales,
        'name':name,
        'email':email,
        'tel':tel,
        'project_list':project_list,
        'agent_list':agent_list,
        'start_date':start_date,
        'end_date':end_date,
        'p_obj':p_obj,
        'ttt':''
        })

"""add student"""
@login_required
def addstudent(request):
    """查用Agent列表"""
    agent = Agent.objects.order_by('id')
    """查用Project列表"""
    pj = Projects.objects.order_by('id')
    """查用Member列表"""

    try:
        p_id=request.session['program']
        p_obj=Projects.objects.get(pk=p_id)
    except:
        p_id=0
        p_obj=''
    members = Members.objects.filter(projects=p_obj,status='7').order_by('id')
    sales = Salesperson.objects.order_by('id')
    return render_to_response('addstudent.html',{'agent':agent,'p_id':int(p_id),'pj':pj,'sales':sales,'members':members,'level':request.session['level']})

"""save student"""
@login_required
def savestudent(request):

    if request.method == 'POST':
        new_data = request.POST.copy()
        if '-1'==new_data['agent_id']:
            agent_id = None
        else:
            agent_id = new_data['agent_id']
            
        if '-1'==new_data['referee_id']:
            referee_id = None
        else:
            referee_id = new_data['referee_id']
        
        if new_data.has_key("graduated"):
            graduated = new_data['graduated']
        else:
            graduated = 0
        
        if new_data.has_key('id'):
            student=Student.objects.get(pk=new_data['id'])
            student.student_id=new_data['student_id'],
            student.name=new_data['name_ch']
            student.name=new_data['name_en']
            student.tel_h=new_data['tel_h']
            student.tel_o=new_data['tel_o']
            student.tel_m=new_data['tel_m']
            student.email=new_data['email']
            student.address=new_data['address']
            student.agent_id=agent_id
            student.projects_id=new_data['program_id']
            student.applytime=new_data['apply_time']
            student.graduated=graduated
            student.referee_id=referee_id
            student.salesperson_id = new_data['salesperson_id']
            student.application_date=new_data['application_date']
            student.application_date_str=new_data['application_date']
            student.acceptance_date=new_data['acceptance_date']
            student.acceptance_date_str=new_data['acceptance_date']
            student.start_date=new_data['start_date']
            student.start_date_str=new_data['start_date']
            student.birthday_date=new_data['birthday_date']
            student.birthday=new_data['birthday_date']
        else:
            student=Student(
            salesperson=Salesperson.objects.get(pk=new_data['salesperson_id']),
            student_id=new_data['student_id'],
            name_ch=new_data['name_ch'],
            name_en=new_data['name_en'],
            tel_h=new_data['tel_h'],
            tel_o=new_data['tel_o'],
            tel_m=new_data['tel_m'],
            email=new_data['email'],
            address=new_data['address'],
            agent_id=agent_id,
            program=Projects.objects.get(pk=new_data['program_id']),
            applytime=new_data['apply_time'],
            graduated=graduated,
            referee=Members.objects.get(pk=referee_id),
            application_date=new_data['application_date'],
            application_date_str=new_data['application_date'],
            acceptance_date=new_data['acceptance_date'],
            acceptance_date_str=new_data['acceptance_date'],
            start_date=new_data['start_date'],
            start_date_str=new_data['start_date'],
            birthday_date=new_data['birthday_date'],
            birthday=new_data['birthday_date'],
            )

        student.save()
        try:            
            return HttpResponseRedirect(new_data['back_url'])
        except:
            return HttpResponseRedirect('/v2/stusearch/')
    return HttpResponseRedirect('/v2/stusearch/')
    
"""edit student"""
@login_required
def edit_stu(request,s_id=""):
    back_url=request.META.get('HTTP_REFERER','/v2/stusearch/')
    student = get_object_or_404(Student, pk=s_id)
    agent = Agent.objects.order_by('id')
    pj = Projects.objects.order_by('id')
    """查用Member列表"""
    members = Members.objects.order_by('id')
    sales = Salesperson.objects.order_by('id')
    """查询其FOLLOW-UP"""
    if student.member:
        f_object=Follow_up.objects.filter(members__id=student.member.id).order_by('id')
    else:
        f_object=[];
    
    today=datetime.date.today()
    today=str(today)
    
    return render_to_response('edit_stu_bak.html',{'student': student,'act':'edit','f_object':f_object,'agent':agent,'pj':pj,'sales':sales,'members':members,'level':request.session['level'],'back_url':back_url,'today':today})


"""edit student"""
@login_required
def edit_student(request,s_id=""):
    err={}
    back_url=request.META.get('HTTP_REFERER','/v2/stusearch/')
    if request.method == 'POST':
        new_data = request.POST.copy()
        student_id=new_data['student_id']
        id=new_data['id']
        file_obj=request.FILES.get('pic', None)
        cv_obj=request.FILES.get('attachcv', None)
        app_obj=request.FILES.get('attachappform', None)
        pro_id=new_data['pro_id']
        saleperson_id=new_data['saleperson_id']
        try:
            p_obj=Projects.objects.get(pk=int(pro_id))
        except:
            p_obj=''

        try:
            ss_obj=Salesperson.objects.get(pk=int(saleperson_id))
        except:
            ss_obj=''

        try:
            student_obj=Student.objects.get(pk=int(id))
        except:
            err.update({'errinfo':'No this student infomation'})
        if file_obj:
            fileName=file_obj.name
            from os.path import basename
            filetype=basename(fileName).split(".").pop().lower()
            import sys
            homedir = str(sys.path[0])
            filedir=homedir+"/static/photos/user/avatar/"
            if os.path.exists(filedir):
                pass
            else:
                os.mkdir(filedir)
            pname=str(student_obj.id)+'.'+filetype
            oldurl=filedir+str(student_obj.id)+'.'+filetype
            pokurl=filedir+str(student_obj.id)+'_i.'+filetype
            im=file(filedir+str(student_obj.id)+'.'+filetype,'wb')
            im.write(file_obj.read())
            im.close()
            image = Image.open(oldurl)
            image.thumbnail((64,64),Image.ANTIALIAS)
            image.save(pokurl,'jpeg') 
            pic=filetype
            student_obj.pic=pic
        if cv_obj:
            fileName=cv_obj.name
            from os.path import basename
            filetype=basename(fileName).split(".").pop().lower()
            import sys
            homedir = str(sys.path[0])
            filedir=homedir+"/static/files/attach/"
            if os.path.exists(filedir):
                pass
            else:
                os.mkdir(filedir)
            im=file(filedir+str(student_obj.id)+'_cv.'+filetype,'wb')
            im.write(cv_obj.read())
            im.close()
            attachcv=str(student_obj.id)+'_cv.'+filetype
            student_obj.attachcv=attachcv
        if app_obj:
            fileName=app_obj.name
            from os.path import basename
            filetype=basename(fileName).split(".").pop().lower()
            import sys
            homedir = str(sys.path[0])
            filedir=homedir+"/static/files/attach/"
            if os.path.exists(filedir):
                pass
            else:
                os.mkdir(filedir)
            im=file(filedir+str(student_obj.id)+'_appform.'+filetype,'wb')
            im.write(app_obj.read())
            im.close()
            attachappform=str(student_obj.id)+'_appform.'+filetype
            student_obj.attachappform=attachappform

        emsaddress=new_data.getlist('emsaddress')
        emsvalue=0
        for i,pid in enumerate(emsaddress):
            if pid:
                try:
                    emsvalue+=int(pid)
                except:
                    pass
        if not err:
            student_obj.student_id=student_id
            student_obj.first_name=new_data['first_name']
            student_obj.last_name=new_data['last_name']
            student_obj.fullname=new_data['fullname']
            student_obj.salesperson=ss_obj
            student_obj.tel_h=new_data['tel_h']
            student_obj.tel_o=new_data['tel_o']
            student_obj.tel_m=new_data['tel_m']
            student_obj.email=new_data['email']
            student_obj.email2=new_data['email2']
            student_obj.address=new_data['address']
            student_obj.appellation=new_data['appellation']
            student_obj.postcode=''
            student_obj.country=new_data['country']
            student_obj.title=new_data['title']
            student_obj.employer=new_data['employer']
            student_obj.program2=new_data['program2']
            student_obj.sale2=new_data['sale2']
            student_obj.birthday=new_data['birthday']
            student_obj.industry=new_data['industry']
            student_obj.mlevel=new_data['mlevel']
            student_obj.officeaddress=new_data['officeaddress']
            student_obj.emsvalue=emsvalue
            student_obj.edu1=new_data['edu1']
            student_obj.edu2=new_data['edu2']
            student_obj.edu3=new_data['edu3']
            student_obj.awarding1=new_data['awarding1']
            student_obj.awarding2=new_data['awarding2']
            student_obj.awarding3=new_data['awarding3']
            student_obj.university1=new_data['university1']
            student_obj.university2=new_data['university2']
            student_obj.university3=new_data['university3']
            student_obj.program=p_obj
            student_obj.remark=new_data['remark']
            if new_data['application_date']:
                e_date_str=""
                dd='00'
                mm='00'
                yyyy='0000'
                try:
                    dd=new_data['application_date'][:2]
                    mm=new_data['application_date'][3:5]
                    yyyy=new_data['application_date'][6:10]
                    e_date_str=yyyy+'-'+mm+'-'+dd
                except:
                    e_date_str=yyyy+'-'+mm+'-'+dd
                application_date=datetime.date(*[int(i) for i in e_date_str.split('-')])
                student_obj.application_date=application_date
                student_obj.application_date_str=new_data['application_date']
            else:
                student_obj.application_date='1900-01-01'
            if new_data['acceptance_date']:
                e_date_str=""
                dd='00'
                mm='00'
                yyyy='0000'
                try:
                    dd=new_data['acceptance_date'][:2]
                    mm=new_data['acceptance_date'][3:5]
                    yyyy=new_data['acceptance_date'][6:10]
                    e_date_str=yyyy+'-'+mm+'-'+dd
                except:
                    e_date_str=yyyy+'-'+mm+'-'+dd
                acceptance_date=datetime.date(*[int(i) for i in e_date_str.split('-')])
                student_obj.acceptance_date=acceptance_date
                student_obj.acceptance_date_str=new_data['acceptance_date']
            else:
                student_obj.acceptance_date='1900-01-01'
            if new_data['start_date']:
                e_date_str=""
                dd='00'
                mm='00'
                yyyy='0000'
                try:
                    dd=new_data['start_date'][:2]
                    mm=new_data['start_date'][3:5]
                    yyyy=new_data['start_date'][6:10]
                    e_date_str=yyyy+'-'+mm+'-'+dd
                except:
                    e_date_str=yyyy+'-'+mm+'-'+dd
                start_date=datetime.date(*[int(i) for i in e_date_str.split('-')])
                student_obj.start_date=start_date
                student_obj.start_date_str=new_data['start_date']
            else:
                student_obj.start_date='1900-01-01'
            if new_data['birthday']:
                e_date_str=""
                dd='00'
                mm='00'
                yyyy='0000'
                try:
                    dd=new_data['birthday'][:2]
                    mm=new_data['birthday'][3:5]
                    yyyy=new_data['birthday'][6:10]
                    e_date_str=yyyy+'-'+mm+'-'+dd
                except:
                    e_date_str=yyyy+'-'+mm+'-'+dd
                birthday_date=datetime.date(*[int(i) for i in e_date_str.split('-')])
                student_obj.birthday_date=birthday_date
                student_obj.birthday=new_data['birthday']
            else:
                student_obj.birthday_date='1900-01-01'

            student_obj.save()
            err.update({'errinfo':'OK'})



    student = get_object_or_404(Student, pk=s_id)
    agent = Agent.objects.order_by('id')
    pj = Projects.objects.order_by('id')
    """查用Member列表"""
    members = Members.objects.order_by('id')
    sales = Salesperson.objects.order_by('id')
    try:
        """查询其FOLLOW-UP"""
        if student.member:
            f_object=Follow_up.objects.filter(members__id=student.member.id).order_by('id')
        else:
            f_object=[];
    except Exception,e:
        f_object=[];
        log.info(e)
    
    today=datetime.date.today()
    today=str(today)
    return render_to_response('edit_stu.html',{'student': student,'err':err,'act':'edit','f_object':f_object,'agent':agent,'pj':pj,'sales':sales,'members':members,'level':request.session['level'],'back_url':back_url,'today':today})


"""program_enrolled"""
@login_required
def program_enrolled(request,s_id=""):
    period=request.REQUEST.get('period',"")
    s_obj = get_object_or_404(Student, pk=s_id)
    p_list = Projects.objects.order_by('id')

    #获取Time table start from
    ttlist=[]
    ttlist2=[]
    isin_list=[]
    pc_list=Project_course_info.objects.filter(project=s_obj.program,is_removed=0).order_by("-year","-class_start")
    for pc in pc_list:
        if pc.period not in isin_list:
            t_dict={}
            t_dict['per']=pc.period[-7:]
            t_dict['pci']=pc
            ttlist.append(t_dict)
            isin_list.append(pc.period)
    #ttlist.sort(reverse=True)
    try:
        ttlist.sort(lambda x,y: cmp(y["per"], x["per"]))
    except:
        pass

    pcs_list=[]
    pcsid=''
    if period!='':
        pcs_list=Project_course_info.objects.filter(project=s_obj.program,is_removed=0,period__gte=period)
        for p in pcs_list:
            pcsid+=str(p.id)+','
    if pcsid:
        pcsid=pcsid[:-1]
    err=''
    #保存学生选课
    if request.method == 'POST':
        if 1:
            new_data = request.POST.copy()
            pp_obj = get_object_or_404(Projects, pk = int(new_data['program_id']))
            pcsids_tem=new_data['pcsid']
            ii=1

            if pcsids_tem:
                id_list=pcsids_tem.split(",")
                
                for i in id_list:
                    periodvar='period'+str(i)
                    modulesvar='modules'+str(i)
                    core_electivevar='core_elective'+str(i)
                    class_startvar='class_start'+str(i)
                    class_endvar='class_end'+str(i)
                    class_date3var='class_date3'+str(i)
                    class_date4var='class_date4'+str(i)
                    class_date5var='class_date5'+str(i)
                    lecturevar='lecture'+str(i)
                    textbookvar='textbook'+str(i)
                    venuevar='venue'+str(i)
                    attochvar='attoch'+str(i)
                    statusvar='status'+str(i)
                    dateofdefervar='dateofdefer'+str(i)
                    var='pcid'+str(i)
                    pcid=request.POST.get(var,'')
                    
                    if pcid!='':
                        try:
                            hc=Program_student_course.objects.get(pcid = int(pcid),student=s_obj,is_removed=0)
                            err=str(ii)+' Record have exist'
                            ii+=1
                        except:
                            project_course_info_id=0
                            try:
                                cc_obj = Project_course_info.objects.get(project = pp_obj,period=new_data[periodvar],is_removed=0)
                                project_course_info_id=cc_obj.id
                            except:
                                pass
                            
                            class_date3 = retTime(new_data[class_date3var])
                            #class_date3 = class_date3[2]+'-'+class_date3[1]+'-'+class_date3[0]

                            class_date4 = retTime(new_data[class_date4var])
                            #class_date4 = class_date4[2]+'-'+class_date4[1]+'-'+class_date4[0]

                            class_date5 = retTime(new_data[class_date5var])
                            #class_date5 = class_date5[2]+'-'+class_date5[1]+'-'+class_date5[0]

                            pinfo=Program_student_course(
                            project=pp_obj,
                            student=s_obj,
                            project_course_info_id=project_course_info_id,
                            period=new_data[periodvar],
                            modules=new_data[modulesvar],
                            core_elective=new_data[core_electivevar],
                            class_start=retTime(new_data[class_startvar]),
                            class_end=retTime(new_data[class_endvar]),
                            lecture=new_data[lecturevar],
                            textbook=new_data[textbookvar],
                            venue=new_data[venuevar],
                            attoch=new_data[attochvar],
                            status=new_data[statusvar],
                            dateofdefer=new_data[dateofdefervar],
                            pcid=int(pcid),
                            is_removed=0,
                            class_date3=class_date3,
                            class_date4=class_date4,
                            class_date5=class_date5,
                            )
                            pinfo.save()
            else:
                if new_data['period']!='':
                    project_course_info_id=0
                    try:
                        cc_obj = Project_course_info.objects.get(project = pp_obj,period=new_data['period'],is_removed=0)
                        project_course_info_id=cc_obj.id
                    except:
                        pass
                    
                    class_start = new_data['class_start'].strip().split('/')
                    class_start = class_start[2]+'-'+class_start[1]+'-'+class_start[0]
                    
                    class_end = new_data['class_end'].strip().split('/')
                    class_end = class_end[2]+'-'+class_end[1]+'-'+class_end[0]

                    pinfo=Program_student_course(
                    project=pp_obj,
                    student=s_obj,
                    project_course_info_id=project_course_info_id,
                    period=new_data['period'].strip(),
                    modules=new_data['modules'].strip(),
                    core_elective=new_data['core_elective'].strip(),
                    class_start=class_start,
                    class_end=class_end,
                    lecture=new_data['lecture'].strip(),
                    textbook=new_data['textbook'].strip(),
                    venue=new_data['venue'].strip(),
                    attoch=new_data['attoch'].strip(),
                    status=new_data['status'].strip(),
                    dateofdefer=new_data['dateofdefer'].strip(),
                    is_removed=0,
                    )
                    pinfo.save()


    #没选中时显示此学生的选课
    today=datetime.date.today()
    today=str(today)
    spc_list=[]
    spcpass_list=[]
    
    spc_list_tmp=Program_student_course.objects.filter(project=s_obj.program,student=s_obj,is_removed=0).order_by('status')

    for sp in spc_list_tmp:
        t_dict={}
        daystart=''
        try:
            day1=sp.class_start
            #d_list=day1.split("/")
            #daystart=d_list[2]+'-'+d_list[1]+'-'+d_list[0]
            daystart = str(day1)
            t_dict['day1']=day1
        except:
            t_dict['day1']=''
        t_dict['textbook']=sp.textbook
        t_dict['per']=sp.period[-7:]
        t_dict['pci']=sp
        if daystart>=today:
            spc_list.append(t_dict)
        else:
            spcpass_list.append(t_dict)


    try:
        spc_list.sort(lambda x,y: cmp(x["day1"], y["day1"]))
    except:
        pass
    try:
        spcpass_list.sort(lambda x,y: cmp(y["day1"], x["day1"]))
    except:
        pass

    t = loader.get_template('program/program_enrolled.html')
    c = RequestContext(request, {
            's_obj':s_obj,
            'p_list':p_list,
            'pc_list':pc_list,
            'ttlist':ttlist,
            'period':period,
            'pcs_list':pcs_list,
            'spc_list':spc_list,
            'spcpass_list':spcpass_list,
            'pcsid':pcsid,
            'err':err,
            'ttt':''
    })
    return HttpResponse(t.render(c))

"""program_enrolled"""
@login_required
def edit_enrolled(request,s_id="",pe_id=""):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    s_obj = get_object_or_404(Student, pk=s_id)
    psc_obj = get_object_or_404(Program_student_course, pk = int(pe_id))
    if request.method == 'POST':
            new_data = request.POST.copy()

            class_start = retTime(new_data['class_start'])
            #class_start = class_start[2]+'-'+class_start[1]+'-'+class_start[0]

            class_end = retTime(new_data['class_end'])
            #class_end = class_end[2]+'-'+class_end[1]+'-'+class_end[0]

            class_date3 = retTime(new_data['class_date3'])
            #class_date3 = class_date3[2]+'-'+class_date3[1]+'-'+class_date3[0]

            class_date4 = retTime(new_data['class_date4'])
            #class_date4 = class_date4[2]+'-'+class_date4[1]+'-'+class_date4[0]

            class_date5 = retTime(new_data['class_date5'])
            #class_date5 = class_date5[2]+'-'+class_date5[1]+'-'+class_date5[0]

            psc_obj.period=new_data['period'].strip()
            psc_obj.modules=new_data['modules'].strip()
            psc_obj.core_elective=new_data['core_elective'].strip()
            psc_obj.class_start=class_start
            psc_obj.class_end=class_end
            psc_obj.lecture=new_data['lecture'].strip()
            psc_obj.textbook=new_data['textbook'].strip()
            psc_obj.venue=new_data['venue'].strip()
            psc_obj.attoch=new_data['attoch'].strip()
            psc_obj.status=new_data['status'].strip()
            psc_obj.dateofdefer=new_data['dateofdefer'].strip()
            psc_obj.class_date3=class_date3
            psc_obj.class_date4=class_date4
            psc_obj.class_date5=class_date5
            psc_obj.taiwankemu=new_data['taiwankemu'].strip()
            psc_obj.save()
            goback="/v2/program_enrolled/"+str(s_id)+"/"
            return HttpResponseRedirect(goback)

    t = loader.get_template('program/edit_enrolled.html')
    c = RequestContext(request, {
            's_obj':s_obj,
            'textbook':psc_obj.textbook,
            'psc_obj':psc_obj,
                        })
    return HttpResponse(t.render(c))




"""pay_record"""
@login_required
def pay_record(request,s_id=""):
    program_id=request.REQUEST.get('program_id',"0")
    s_obj = get_object_or_404(Student, pk=s_id)
    p_list = Projects.objects.order_by('id')
    sale_list = Salesperson.objects.order_by('id')
    pp_obj=''
    errinfo=''
    try:
        pp_obj = get_object_or_404(Projects, pk = int(program_id))
    except:
        pp_obj=''

    if request.method == 'POST':
        new_data = request.POST.copy()
        fullpay=request.POST.get("fullpay",'0')
        try:
            fullpay=int(fullpay)
        except:
            fullpay=0
        pp_obj = get_object_or_404(Projects, pk = int(new_data['program_id']))
        date1 = retTime(new_data['date1'].strip())
        date2 = retTime(new_data['date2'].strip())
        date3 = retTime(new_data['date3'].strip())
        date4 = retTime(new_data['date4'].strip())
        date1_paid = retTime(new_data['date1_paid'].strip())
        date2_paid = retTime(new_data['date2_paid'].strip())
        date3_paid = retTime(new_data['date3_paid'].strip())
        date4_paid = retTime(new_data['date4_paid'].strip())

        try:
            pay_obj=Student_Payment_Record.objects.get(project=pp_obj,student=s_obj)
            pay_obj.project=pp_obj
            pay_obj.fullpay=fullpay
            pay_obj.moneytype=new_data['moneytype'].strip()
            pay_obj.amount=new_data['amount'].strip()
            pay_obj.discount=new_data['discount'].strip()
            pay_obj.discount_money=new_data['discount_money'].strip()
            pay_obj.referredby=new_data['referredby'].strip()
            pay_obj.module_wavied=new_data['module_wavied'].strip()
            pay_obj.module_wavied_money=new_data['module_wavied_money'].strip()
            pay_obj.subtotal_money=new_data['subtotal_money'].strip()
            pay_obj.date1=date1
            pay_obj.date2=date2
            pay_obj.date3=date3
            pay_obj.date4=date4
            pay_obj.datefee=new_data['datefee'].strip()
            pay_obj.datereg=new_data['datereg'].strip()
            pay_obj.date1_money=new_data['date1_money'].strip()
            pay_obj.date2_money=new_data['date2_money'].strip()
            pay_obj.date3_money=new_data['date3_money'].strip()
            pay_obj.date4_money=new_data['date4_money'].strip()
            pay_obj.datefee_money=new_data['datefee_money'].strip()
            pay_obj.datereg_money=new_data['datereg_money'].strip()
            pay_obj.date1_invoice=new_data['date1_invoice'].strip()
            pay_obj.date2_invoice=new_data['date2_invoice'].strip()
            pay_obj.date3_invoice=new_data['date3_invoice'].strip()
            pay_obj.date4_invoice=new_data['date4_invoice'].strip()
            pay_obj.datefee_invoice=new_data['datefee_invoice'].strip()
            pay_obj.datereg_invoice=new_data['datereg_invoice'].strip()
            pay_obj.date1_paid=date1_paid
            pay_obj.date2_paid=date2_paid
            pay_obj.date3_paid=date3_paid
            pay_obj.date4_paid=date4_paid
            pay_obj.datefee_paid=new_data['datefee_paid'].strip()
            pay_obj.datereg_paid=new_data['datereg_paid'].strip()
            pay_obj.date1_paiy_by=new_data['date1_paiy_by'].strip()
            pay_obj.date2_paiy_by=new_data['date2_paiy_by'].strip()
            pay_obj.date3_paiy_by=new_data['date3_paiy_by'].strip()
            pay_obj.date4_paiy_by=new_data['date4_paiy_by'].strip()
            pay_obj.datefee_paiy_by=new_data['datefee_paiy_by'].strip()
            pay_obj.datereg_paiy_by=new_data['datereg_paiy_by'].strip()
            pay_obj.date1_handed_by=new_data['date1_handed_by'].strip()
            pay_obj.date2_handed_by=new_data['date2_handed_by'].strip()
            pay_obj.date3_handed_by=new_data['date3_handed_by'].strip()
            pay_obj.date4_handed_by=new_data['date4_handed_by'].strip()
            pay_obj.datefee_handed_by=new_data['datefee_handed_by'].strip()
            pay_obj.datereg_handed_by=new_data['datereg_handed_by'].strip()
            pay_obj.moneytypedate1=new_data['moneytypedate1'].strip()
            pay_obj.moneytypedate2=new_data['moneytypedate2'].strip()
            pay_obj.moneytypedate3=new_data['moneytypedate3'].strip()
            pay_obj.moneytypedate4=new_data['moneytypedate4'].strip()
            pay_obj.moneytypedatefee=new_data['moneytypedatefee'].strip()
            pay_obj.moneytypedatereg=new_data['moneytypedatereg'].strip()
            pay_obj.save()
            errinfo='Option Success'
        except:
            pay_obj=Student_Payment_Record(
            project=pp_obj,
            student=s_obj,
            fullpay=fullpay,
            moneytype=new_data['moneytype'].strip(),
            amount=new_data['amount'].strip(),
            discount=new_data['discount'].strip(),
            discount_money=new_data['discount_money'].strip(),
            referredby=new_data['referredby'].strip(),
            module_wavied=new_data['module_wavied'].strip(),
            module_wavied_money=new_data['module_wavied_money'].strip(),
            subtotal_money=new_data['subtotal_money'].strip(),
            date1=date1,
            date2=date2,
            date3=date3,
            date4=date4,
            datefee=new_data['datefee'].strip(),
            datereg=new_data['datereg'].strip(),
            date1_money=new_data['date1_money'].strip(),
            date2_money=new_data['date2_money'].strip(),
            date3_money=new_data['date3_money'].strip(),
            date4_money=new_data['date4_money'].strip(),
            datefee_money=new_data['datefee_money'].strip(),
            datereg_money=new_data['datereg_money'].strip(),
            date1_invoice=new_data['date1_invoice'].strip(),
            date2_invoice=new_data['date2_invoice'].strip(),
            date3_invoice=new_data['date3_invoice'].strip(),
            date4_invoice=new_data['date4_invoice'].strip(),
            datefee_invoice=new_data['datefee_invoice'].strip(),
            datereg_invoice=new_data['datereg_invoice'].strip(),
            date1_paid=date1_paid,
            date2_paid=date2_paid,
            date3_paid=date3_paid,
            date4_paid=date4_paid,
            datefee_paid=new_data['datefee_paid'].strip(),
            datereg_paid=new_data['datereg_paid'].strip(),
            date1_paiy_by=new_data['date1_paiy_by'].strip(),
            date2_paiy_by=new_data['date2_paiy_by'].strip(),
            date3_paiy_by=new_data['date3_paiy_by'].strip(),
            date4_paiy_by=new_data['date4_paiy_by'].strip(),
            datefee_paiy_by=new_data['datefee_paiy_by'].strip(),
            datereg_paiy_by=new_data['datereg_paiy_by'].strip(),
            date1_handed_by=new_data['date1_handed_by'].strip(),
            date2_handed_by=new_data['date2_handed_by'].strip(),
            date3_handed_by=new_data['date3_handed_by'].strip(),
            date4_handed_by=new_data['date4_handed_by'].strip(),
            datefee_handed_by=new_data['datefee_handed_by'].strip(),
            datereg_handed_by=new_data['datereg_handed_by'].strip(),
            moneytypedate1=new_data['moneytypedate1'].strip(),
            moneytypedate2=new_data['moneytypedate2'].strip(),
            moneytypedate3=new_data['moneytypedate3'].strip(),
            moneytypedate4=new_data['moneytypedate4'].strip(),
            moneytypedatefee=new_data['moneytypedatefee'].strip(),
            moneytypedatereg=new_data['moneytypedatereg'].strip(),
            is_removed=0,
            )
            pay_obj.save()
            errinfo='Save Success'

    if not pp_obj:
        pp_obj=s_obj.program
    try:
        pay_obj=Student_Payment_Record.objects.get(project=pp_obj,student=s_obj)
    except:
        pay_obj=''
    amountmoney_m=''
    try:
        if program_id==0 or program_id=='0':
            program_id=s_obj.program.id
        if int(program_id)==4:
            amountmoney_m=198000
        if int(program_id)==16:
            amountmoney_m=258000
        if int(program_id)==3:
            amountmoney_m=16400
        if int(program_id)==17:
            amountmoney_m=188000
    except:
        pass

    #other program payment record
    ppay_list=Student_Payment_Record.objects.filter(student=s_obj)

    t = loader.get_template('payment/pay_record.html')
    c = RequestContext(request, {
            's_obj':s_obj,
            'p_list':p_list,
            'sale_list':sale_list,
            'pay_obj':pay_obj,
            'pp_obj':pp_obj,
            'ppay_list':ppay_list,
            'errinfo':errinfo,
            'amountmoney_m':amountmoney_m,
            'ttt':pay_obj
    })
    return HttpResponse(t.render(c))


"""del student"""
@login_required
def del_stu(request,s_id=""):
   
    Student.objects.filter(pk=s_id).delete()
    try:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
    except:
        return HttpResponseRedirect('/v2/stusearch/')

"""del student"""
@login_required
def del_student_enrolled_course(request,s_id="",sc_id=""):
    period=request.REQUEST.get('period',"")
    p_obj = get_object_or_404(Program_student_course, pk = int(sc_id))
    p_obj.is_removed=1
    p_obj.save()

    burl="/v2/program_enrolled/"+str(s_id)+"/?period="+str(period)
    return HttpResponseRedirect(burl)

#同步学生选课表中的时间与基本课程信息表中的时间
def setdays (request):
    s_list=Program_student_course.objects.filter(is_removed=0)
    i=0
    for s in s_list:
        try:
            c_obj = Project_course_info.objects.get(project = s.project,period=s.period,is_removed=0)
            s.class_date3=c_obj.class_date3
            s.class_date4=c_obj.class_date4
            s.class_date5=c_obj.class_date5
            s.save()
            i+=1
        except:
            pass
    return HttpResponse(str(i))


def retTime(date):
    if date:
        date = date.split('/')
        date = date[2]+'-'+date[1]+'-'+date[0]
        #begy,begm,begd = time.strptime(date,'%Y-%m-%d')[0:3]
        #date = datetime.datetime(begy,begm,begd)
    else:
        date = None
    
    return date